import Docx from "./docx";
import Pdf from "./pdf";
import C2d from "./c2d";
import Markdown from "./markdown";

// 初始化文件操作类字典
const fileMap = new Map();
const docx = new Docx();
fileMap.set(docx.getExtension(), docx);
const pdf = new Pdf();
fileMap.set(pdf.getExtension(), pdf);
const c2d = new C2d();
fileMap.set(c2d.getExtension(), c2d);
const markdown = new Markdown();
fileMap.set(markdown.getExtension(), markdown);

class Cat2DocFile {
    #content = null;
    constructor(content) {
        this.#content = content.$el;
    }
    /** 导出文件 */
    export(fileName, element) {
        if(!fileName) {
            throw new Error('The file name cannot be empty!')
        }
        let fileExtension = Cat2DocFile.getExtension(fileName);
        if(!fileExtension) {
            throw new Error('Unknown file type!');
        }
        fileExtension = fileExtension.toUpperCase();
        if(fileMap.has(fileExtension)) {
            return new Promise((resolve,reject)=>{
                return fileMap.get(fileExtension).export(fileName, element).then(value=>{
                    resolve(value);
                }).catch(err=>{
                    reject(err);
                })
            });
        } else {
            throw new Error('The import of this file is not supported at this time!');
        }
    }

    /**
     * 导入文件
     * @param file  文件
     * @param type  文件类型
     * @returns {Promise<unknown>}
     */
    import(file, type) {
        if(!file) {
            throw new Error('The file cannot be empty!')
        }
        let fileExtension = type||Cat2DocFile.getExtension(file.name);
        if(!fileExtension) {
            throw new Error('Unknown file type!');
        }
        fileExtension = fileExtension.toUpperCase();
        if(fileMap.has(fileExtension)) {
            return new Promise((resolve,reject)=>{
                fileMap.get(fileExtension).import(file).then(value=>{
                    resolve(value);
                }).catch(err=>{
                    reject(err);
                })
            });
        } else {
            throw new Error('The import of this file is not supported at this time!');
        }
    }

    /** 获取扩展名 */
    static getExtension(fileName) {
        return fileName.split(".").pop();
    }
}

export default Cat2DocFile;
